/**
 * 
 */
package info.niwota.frames;

import android.graphics.Bitmap;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;

/**
 * @author qiangli
 * 
 */
public class PhotoFrameImageAdapter extends BaseAdapter {
	private static final String TAG = "PhotoFrameImageAdapter";
	private static final int CACHE_CAPACITY = 512;

	private final LruCache<Integer, Bitmap> cache = new LruCache<Integer, Bitmap>(
			CACHE_CAPACITY);

	private static class ViewHolder {
		private ImageView image;
	}

	private ImageList images;

	private PhotoFrameActivity context;

	public PhotoFrameImageAdapter(PhotoFrameActivity c) {
		context = c;
	}

	public int getCount() {
		return (images == null ? 0 : images.getCount());
	}

	public Object getItem(int position) {
		return position;
	}

	public long getItemId(int position) {
		return position;
	}

	public View getView(int position, View convertView, ViewGroup parent) {
		if (Debug.DEBUG) {
			Log.d(TAG, "getView position: " + position);
		}
		ViewHolder holder;
		if (convertView == null) {
			ImageView v = new ImageView(context);
			convertView = v; // inflater.inflate(R.layout.list_item2, null);
			holder = new ViewHolder();
			// holder.image = (ImageView)
			// convertView.findViewById(R.id.list_item2_icon);
			holder.image = v;
			v.setLayoutParams(new Gallery.LayoutParams(80, 80));
			v.setScaleType(ImageView.ScaleType.FIT_XY);
			v.setBackgroundResource(R.drawable.picture_frame_background);
			convertView.setTag(holder);
		} else {
			holder = (ViewHolder) convertView.getTag();
		}
		// cache?
		// IImage img = images.getImageAt(position);
		// Bitmap bm = img.miniThumbBitmap();
		try {
			Bitmap bm = getImageAt(position);
			holder.image.setImageBitmap(bm);
		} catch (Exception e) {
			showError(e);
			
			if (Debug.DEBUG) {
				e.printStackTrace();
			}
		}
		return convertView;
	}

	private Bitmap getImageAt(int i) {
		if (images == null) {
			Log.d(TAG, "getImageAt  [" + i + "]: not found. " );
			return null;
		}
		Bitmap result = cache.get(i);
		if (result == null) {
			synchronized (this) {
				IImage img = images.getImageAt(i);
				if (Debug.DEBUG) {
					Log.d(TAG, "getImageAt  [" + i + "] " + img.fullSizeImageUri());
				}
				result = img.miniThumbBitmap();
				cache.put(i, result);
			}
		}
		return result;
	}

	public void clear() {
		images = null;
		cache.clear();
	}

	public void load(ImageFrame frame) {
		if (Debug.DEBUG) {
			Log.d(TAG, "load frame: " + frame +" size: " + frame.getCount());
		}
		this.images = frame.getList();
		cache.clear();
	}
	
	public void refresh() {
		notifyDataSetChanged();
	}
	
	private void showError(Exception e) {
		if (context != null) {
			context.showBgError(e);
		}
	}
}
